import { useLookup } from '@/utils/hooks/useLookup';
import type { DemoMainFlowDto } from '@/api/avic/demo/DemoMainFlowApi'; // 引入模块DTO
// eslint-disable-next-line max-len
import { getDemoMainFlow, saveDemoMainFlow, checkDemoUniqueUnique, saveFormAndStartProcess } from '@/api/avic/demo/DemoMainFlowApi'; // 引入模块API
import { createEditor } from '@wangeditor/editor'; // 引入富文本依赖
import { useRichText } from '@/utils/hooks/useRichText'; // 引入富文本相关配置及方法
import { uploadMultipleFileElements } from '@/components/file-upload/components/util'; // 引入多附件上传组件相关方法
import {
  default as flowUtils,
  startFlowByFormCode,
  closeFlowLoading,
  openFlowDetail,
  getFieldAuth,
  getFieldVisible,
  getFieldDisabled,
  getFieldRequired
} from '@/views/avic/bpm/bpmutils/FlowUtils.js';

export const emits = ['reloadData', 'close'];
export function useDemoMainFlowForm() {
  const { proxy, props, emit } = getCurrentInstance();
  const form = ref<DemoMainFlowDto>({
    uploadFile: {
      file1: null
    }
  });
  const formRef = ref(null);
  const formCode = 'DemoMainFlow';
  const openType = ref('add'); // 流程表单的打开方式，add: 流程中心打开, edit: 待办打开
  const bpmParams = ref<any>({}); // 存储来自prop或者url的参数信息
  const bpmButtonParams = ref<any>({}); // 提交按钮传递的参数
  const bpmResult = ref(null); // 表单驱动方式启动流程的流程数据
  const rules: Record<string, Rule[]> = {
    demoUserId: [{ required: true, message: '用户不能为空', trigger: 'change' }],
    secretLevel: [{ required: true, message: '密级不能为空', trigger: 'change' }],
    demoNotnull: [{ required: true, message: '必填不能为空', trigger: 'change' }],
    demoPhone: [proxy.$validateRegExp('phone')],
    demoEmail: [proxy.$validateRegExp('email')],
    demoWebsite: [proxy.$validateRegExp('url')],
    demoUnique: [
      { required: true, message: '唯一值不能为空', trigger: 'change' },
      { validator: (rule, value) => validateDemoUniqueUnique(rule, value), trigger: 'blur' }
    ]
  };
  const demoSubFlowEdit = ref();
  const layout = {
    labelCol: { flex: '140px' },
    wrapperCol: { flex: '1' }
  };
  const colLayout = proxy.$colLayout2; // 调用布局公共方法
  const loading = ref(false);
  const uploadFile = {
    file1: ref(null)
  }; // 附件ref
  const autoCode = ref(null); // 自动编码ref
  const { lookupList } = useLookup(['PLATFORM_SEX', 'PLATFORM_CHECK_TYPE', 'PLATFORM_DEGREE']);
  const editorRef = shallowRef(null); // 编辑器实例，必须用 shallowRef
  const { toolbarConfig, editorConfig, onCreated, dealRichText, convertImageSrc } = useRichText(
    editorRef,
    'demoMainFlowDemoRichtext',
    'DEMO_MAIN_FLOW'
  );
  const authJson = ref(null);

  if (props.params) {
    bpmParams.value = props.params;
  } else {
    if (proxy.$route) {
      bpmParams.value = proxy.$route.query;
    }
  }
  if (bpmParams.value) {
    // 加载流程数据
    form.value.id = bpmParams.value.id;
    openType.value = bpmParams.value.id ? 'edit' : 'add';
  }

  onMounted(() => {
    if (props.formId || form.value.id) {
      // 编辑详情页面加载数据
      getFormData(props.formId || form.value.id);
    } else {
      // 添加表单的初始值
      initForm();
    }
  });
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  });
  /**
   * 编辑详情页面加载数据
   * @param {String} id 行数据的id
   */
  function getFormData(id) {
    if (!id) {
      return;
    }
    loading.value = true;
    getDemoMainFlow(id)
      .then(async (res) => {
        if (res.data) {
          form.value = Object.assign({}, form.value, res.data, { id });
          // 处理数据
          form.value.demoCheckbox = form.value.demoCheckbox?.toString()?.split(';'); // 处理复选框数据
          form.value.demoSelectMultiple = form.value.demoSelectMultiple?.toString()?.split(';'); // 处理多选下拉数据
          if (autoCode.value) {
            autoCode.value.setCodeValue(form.value.demoCode);
          }
          // 处理富文本
          await dealRichText(form.value.demoRichtext);
          // 详情表单 富文本是否可编辑
          if (fieldDisabled('demoRichtext')) {
            editorRef.value.disable();
          }
          loading.value = false;
        } else {
          initForm();
          loading.value = false;
        }
      })
      .catch(() => {
        proxy.$message.warning('获取表单数据失败！');
        loading.value = false;
      });
  }
  /** 保存 */
  function saveForm(params) {
    formRef.value
      .validate()
      .then(async () => {
        demoSubFlowEdit.value.validate(async (validate) => {
          if (!validate) {
            closeFlowLoading(props.bpmInstanceObject);
            return;
          }
          loading.value = true;
          const postData = proxy.$lodash.cloneDeep(form.value);
          const subInfoList = demoSubFlowEdit.value.getChangedData(); // 获取子表数据
          // 处理数据
          postData.demoSubFlowList = subInfoList; // 挂载子表数据
          postData.demoCheckbox = postData.demoCheckbox?.join(';'); // 处理复选框数据
          postData.demoSelectMultiple = postData.demoSelectMultiple?.join(';'); // 处理多选下拉数据
          postData.demoSwitch = postData.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
          if (autoCode.value) {
            // 获取编码码段值
            postData.demoCode = autoCode.value.getSegmentValue();
          }
          // 处理富文本
          const editorHtmljsonCopy = proxy.$lodash.cloneDeep(editorRef.value.children);
          convertImageSrc(editorHtmljsonCopy);
          const newEditor = createEditor({ content: editorHtmljsonCopy });
          const newEditorHtml = newEditor.getHtml();
          postData.demoRichtext = newEditorHtml;
          // 发送请求
          saveDemoMainFlow(postData)
            .then((res) => {
              if (res.success) {
                if (props.bpmInstanceObject) {
                  bpmButtonParams.value = { params, result: res.data };
                }
                if (!form.value.id) {
                  form.value.id = res.data;
                }
                // 校验多附件区域的附件密级并上传
                uploadMultipleFileElements({
                  uploaderInstances: uploadFile,
                  formId: form.value.id || res.data,
                  secretLevel: form.value.secretLevel,
                  onSuccess: successCallback,
                  onError: errorCallback
                });
              } else {
                errorCallback();
              }
            })
            .catch(() => {
              errorCallback();
            });
        });
      })
      .catch((error) => {
        closeFlowLoading(props.bpmInstanceObject);
        loading.value = false;
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(formRef, error);
      });
  }
  /** 设置添加表单的初始值 */
  function initForm() {
    // 初始化光标定位
    nextTick(() => {
      closeFlowLoading(props.bpmInstanceObject);
    });
  }
  /** 校验通过后，读取要启动的流程模板 */
  function getBpmDefine(formData) {
    startFlowByFormCode({
      formCode,
      formData,
      callback: (bpmDefinedInfo) => {
        if (!bpmDefinedInfo) {
          loading.value = false;
        } else {
          saveAndStartProcess(bpmDefinedInfo);
        }
      }
    });
  }
  /** 保存并启动流程 */
  async function saveAndStartProcess(params) {
    formRef.value
      .validate()
      .then(() => {
        demoSubFlowEdit.value.validate((validate) => {
          if (!validate) {
            return;
          }
          loading.value = true;
          // 处理数据
          const postData = proxy.$lodash.cloneDeep(form.value);
          const subInfoList = demoSubFlowEdit.value.getChangedData(); // 获取子表数据
          postData.demoSubFlowList = subInfoList; // 挂载子表数据
          postData.demoCheckbox = postData.demoCheckbox?.join(';'); // 处理复选框数据
          postData.demoSelectMultiple = postData.demoSelectMultiple?.join(';'); // 处理多选下拉数据
          postData.demoSwitch = postData.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
          if (autoCode.value) {
            // 获取编码码段值
            postData.demoCode = autoCode.value.getSegmentValue();
          }
          // 处理富文本
          const editorHtmljsonCopy = proxy.$lodash.cloneDeep(editorRef.value.children);
          convertImageSrc(editorHtmljsonCopy);
          const newEditor = createEditor({ content: editorHtmljsonCopy });
          const newEditorHtml = newEditor.getHtml();
          postData.demoRichtext = newEditorHtml;
          // 点击保存并启动流程按钮触发
          if (!props.bpmInstanceObject && !params.dbid) {
            // 校验表单并选择需要启动的流程模板
            getBpmDefine(postData);
          } else {
            const param = {
              processDefId: params.dbid || bpmParams.value.defineId,
              formCode,
              postData
            };
            // 发送请求
            saveFormAndStartProcess(param)
              .then((res) => {
                if (res.success) {
                  if (props.bpmInstanceObject) {
                    bpmButtonParams.value = { params, result: res.data };
                  }
                  bpmResult.value = res.data;
                  if (!form.value.id) {
                    form.value.id = res.data.formId;
                  }
                  // 校验多附件区域的附件密级并上传
                  uploadMultipleFileElements({
                    uploaderInstances: uploadFile,
                    formId: form.value.id || res.data,
                    secretLevel: form.value.secretLevel,
                    onSuccess: successCallback,
                    onError: errorCallback
                  });
                } else {
                  errorCallback();
                }
              })
              .catch(() => {
                errorCallback();
              });
          }
        });
      })
      .catch((error) => {
        closeFlowLoading(props.bpmInstanceObject);
        loading.value = false;
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(formRef, error);
      });
  }
  /** 保存、保存并启动流程处理成功后的逻辑 */
  function successCallback() {
    if (props.bpmInstanceObject) {
      closeFlowLoading(props.bpmInstanceObject);
      // 刷新表单版本
      getFormData(form.value.id);
      // 刷新子表数据
      demoSubFlowEdit.value.getList();
      // 回调选人等流程按钮事件
      if (bpmButtonParams.value.params.callback) {
        bpmButtonParams.value.params.callback(bpmButtonParams.value.result);
        bpmButtonParams.value = {};
      }
    } else {
      // 添加页面-保存并启动流程后，打开流程详情页
      if (bpmResult.value) {
        openFlowDetail(bpmResult.value, props.bpmOperatorRefresh);
      }
      proxy.$message.success('保存成功！');
      emit('reloadData');
      emit('close');
    }
  }
  /** 数据保存失败的回调 */
  function errorCallback() {
    if (props.bpmInstanceObject) {
      closeFlowLoading(props.bpmInstanceObject);
    } else {
      loading.value = false;
    }
  }
  /** 附件上传完之后的回调函数 */
  function afterUploadEvent(_successFile, errorFile) {
    if (errorFile.length > 0) {
      errorCallback();
      // 有附件保存失败的处理
      proxy.$message.error('附件保存失败！');
      emit('reloadData');
      emit('close');
    } else {
      // 所有附件都保存成功的处理
      successCallback();
    }
  }
  /** 异步校验唯一值唯一 */
  async function validateDemoUniqueUnique(_rule, value) {
    if (value) {
      const res = await checkDemoUniqueUnique({
        demoUnique: value,
        id: bpmParams.value.id || props.formId || form.value.id || ''
      });
      if (res.success) {
        if (res.data) {
          return Promise.resolve();
        }
        return Promise.reject('唯一值已存在!');
      }
      return Promise.reject('唯一值唯一性校验失败!');
    }
    return Promise.resolve();
  }
  /** 返回关闭事件 */
  function closeModal() {
    emit('close');
  }
  /** 点击流程按钮的前置事件 */
  function beforeClickBpmButtons() {
    return new Promise((resolve) => {
      resolve(true);
    });
  }
  /** 点击流程按钮的后置事件 */
  function afterClickBpmButtons() {
    return new Promise((resolve) => {
      resolve(true);
    });
  }
  /** 表单字段是否显示 */
  function fieldVisible(fieldName) {
    checkAuthJson();
    return getFieldVisible(authJson.value, fieldName);
  }
  /** 表单字段是否可编辑 */
  function fieldDisabled(fieldName) {
    checkAuthJson();
    return getFieldDisabled(authJson.value, fieldName, props.bpmInstanceObject);
  }
  /** 表单字段是否显示 */
  function fieldRequired(fieldName) {
    checkAuthJson();
    return getFieldRequired(authJson.value, fieldName, rules, props.bpmInstanceObject);
  }
  /** 表单附件是否必填(按elementId) */
  function attachmentRequired(fieldName) {
    const res = flowUtils.attachmentRequired(props.bpmInstanceObject, fieldName);
    return res;
  }
  /** 表单附件是否显示(按elementId) */
  function attachmentAccessibility(fieldName) {
    return flowUtils.attachmentAccessibility(props.bpmInstanceObject, fieldName);
  }
  function checkAuthJson() {
    if (authJson.value == null) {
      authJson.value = getFieldAuth(props.bpmInstanceObject);
    }
  }

  return {
    form,
    formRef,
    bpmParams,
    rules,
    layout,
    colLayout,
    loading,
    lookupList,
    uploadFile,
    afterUploadEvent,
    attachmentRequired,
    attachmentAccessibility,
    autoCode,
    toolbarConfig,
    editorConfig,
    editorRef,
    onCreated,
    saveForm,
    saveAndStartProcess,
    closeModal,
    fieldVisible,
    fieldDisabled,
    fieldRequired,
    beforeClickBpmButtons,
    afterClickBpmButtons,
    demoSubFlowEdit
  };
}
